package com.example.demo.util;

import com.example.demo.enums.CommonEnum;
import org.springframework.util.Assert;

import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 密码验证工具.
 */
public class PasswordUtils {

    public static boolean isPasswordExpired(String password, Date updateDate) {
        Assert.notNull(password, "密码不能为空.");
        //如果密码是123456, 则认为密码过期
        if(CommonEnum.DEFAULT_PWD_ENCRYPT.getValue().equals(password)
            || updateDate == null) {
            return true;
        }
        Calendar lastUpdateTime = Calendar.getInstance();
        lastUpdateTime.setTime(updateDate);
        lastUpdateTime.add(Calendar.DAY_OF_YEAR, Integer.parseInt(CommonEnum.DEFAULT_EXPIRE_DAY.getValue()));
        Calendar now = Calendar.getInstance();
        return now.after(lastUpdateTime);
    }

    // 判断密码是否强壮
    public static boolean isPasswordStrong(String password) {
        if(password.length() < 8) {
            return false;
        }
        Pattern p = Pattern.compile("[-=;'~`,./!@#$%^&*()_+|<>?]+");
        Matcher m = p.matcher(password);
        if (!m.find()) {
            return false;
        }

        p = Pattern.compile("[0-9]");
        m = p.matcher(password);
        if (!m.find()) {
            return false;
        }

        p = Pattern.compile("[a-z]");
        m = p.matcher(password);
        if (!m.find()) {
            return false;
        }
        p = Pattern.compile("[A-Z]");
        m = p.matcher(password);
        if (!m.find()) {
            return false;
        }
        return true;
    }
}
